package com.version1_2.service.implement;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.util.format.TimeFormat;
import com.util.page.GetPageModel;
import com.util.property.Properties;
import com.version1_1.dao.PageDao;
import com.version1_1.model.MainPageModel;
import com.version1_1.service.PageService;
import com.version1_2.dao.PageDao1_2;
import com.version1_2.service.PageService1_2;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageService12Impl implements PageService1_2 {

    /*创建Log4j对象*/
    private static final Logger LOGGER = Logger.getLogger(PageService12Impl.class);

    @Autowired
    private PageDao1_2 pageDao12; // 自定义1.2Dao层

    @Autowired
    private PageDao pageDao;


    /**
     * @param pageId
     * @return
     * @Description: TODO(分享出去的文章获取页面信息)
     */
    @Override
    public String getPageInfoShare(int pageId) {
        List pageContentList = pageDao.getPageInfo(pageId);

        if (pageContentList == null || pageContentList.isEmpty()) {
            return "";
        }

        Map resultMap = (Map) pageContentList.get(0);

        //得到标题和页面内容
        String firstTitle = (String) resultMap.get("firstTitle");
        String pageContent = (String) resultMap.get("pageContent");
        String pageFrom = (String) resultMap.get("pageFrom");
        String pageDate = resultMap.get("pageDate").toString();
        String imageSrc = (String) resultMap.get("imageSrc");
        long readNumber = (long) resultMap.get("readNumber");
        String sourceAddress = (String) resultMap.get("sourceAddress");

        if (sourceAddress == null) {
            sourceAddress = "";
        }

        String htmlString = "";

        String pageModelStr = GetPageModel.getPageShareModelStr(Properties.Page_ModelURLShare);
        htmlString = pageModelStr;
        htmlString = htmlString.replace("{kuibu_pageTitle}", firstTitle);
        htmlString = htmlString.replace("{kuibu_pageReadNumber}", String.valueOf(readNumber));
        htmlString = htmlString.replace("{kuibu_pageFrom}", pageFrom);
        htmlString = htmlString.replace("{kuibu_pageContent}", pageContent);
        htmlString = htmlString.replace("{kuibu_pageTitleImage}", imageSrc + Properties.ImageHighQuality);
        htmlString = htmlString.replace("{kuibu_pageDate}", pageDate);
        htmlString = htmlString.replace("{kuibu_sourceAddress}", sourceAddress);

        return htmlString;
    }


    /**
     * @Description: 搜索文章标题
     */
    @Override
    public String searchPage(String key) {
        List<Map<String, Object>> searchList = pageDao12.searchPage(key); // 搜索结果
        boolean hasResult = true; // 是否有搜索结果
        Map<String, Object> searchPageMap = new HashMap<>(); // 搜索结果Map

        if (searchList.isEmpty()) {
            LOGGER.info("根据关键词未搜索到文章,搜索关键字为: " + key);
            hasResult = false;
        } else {
            for (int i = 0; i < searchList.size(); i++) {
                Map<String, Object> temp = searchList.get(i);
                temp.replace("imageSrc", temp.get("imageSrc") + Properties.ImageLowQuality);
            }
        }

        searchPageMap.put("hasResult", hasResult);
        searchPageMap.put("searchResult", searchList);
        return JSON.toJSONString(searchPageMap);
    }

    /**
     * @description: 获取三级分类页面预览信息数据
     */
    @Override
    @Cacheable(value = {"thirdTypePageCacheVersion1_2"})
    public String getThirdPage(int secondType, String thirdTypeName,
                               int pageNumber, int pageSize) {
        List pageList = pageDao12.getThirdPageList(secondType, thirdTypeName,
                pageNumber, pageSize);
        boolean isLast = false;
        Map<String, Object> getThirdPageMap = new HashMap<>();

        if (pageList == null || pageList.isEmpty()) {
            isLast = true;
        } else {
            for (int i = 0; i < pageList.size(); i++) {
                Map pageMap = (Map) pageList.get(i);
                pageMap.replace("imageSrc", (String) pageMap.get("imageSrc") + Properties.ImageQuality);
            }
        }

        getThirdPageMap.put("isLast", isLast);
        getThirdPageMap.put("result", pageList);
        return JSON.toJSONString(getThirdPageMap);
    }

    /**
     * @Description: 获取未登陆用户主页面预览信息
     */
    @Override
    @Cacheable(value = {"noLoginMainPageVersion1_2"})
    @CacheEvict(value = "noLoginMainPageVersion1_2", condition = "#cacheTag==true", allEntries = true)
    public String getNewMainPageNoLogin(JSONObject jsonObject, int pageNumber, int pageSize, boolean cacheTag) {
        MainPageModel mainPageModel = pageDao12.getNewPageListNoLogin(jsonObject,
                pageNumber, pageSize);

        // 处理mainPageModel中图片的URL路径
        if (mainPageModel.getPageList() != null) {
            for (Map pageMap : mainPageModel.getPageList()) {
                pageMap.replace("imageSrc", (String) pageMap.get("imageSrc") + Properties.ImageQuality);
            }
        }

        if (mainPageModel.getTitleList() != null) {
            for (Map titleMap : mainPageModel.getTitleList()) {
                titleMap.replace("imageSrc", (String) titleMap.get("imageSrc") + Properties.ImageHighQuality);
            }
        }

        return mainPageModel.jsonSerialize();
    }


    /**
     * @description: 获取登陆用户主页面预览信息数据
     */
    @Override
    @Cacheable(value = {"loginMainPageVersion1_2"})
    @CacheEvict(value = "loginMainPageVersion1_2", condition = "#cacheTag==true", allEntries = true)
    // 要指定allEntries为true才能刷新缓存
    public String getNewMainPage(int userId, int firstType, int pageNumber,
                                 int pageSize, boolean cacheTag) {

        MainPageModel mainPageModel = pageDao12.getNewMainPage(userId, firstType, pageNumber,
                pageSize);

        // 处理mainPageModel中图片的URL路径
        if (mainPageModel.getPageList() != null) {
            for (Map pageMap : mainPageModel.getPageList()) {
                pageMap.replace("imageSrc", (String) pageMap.get("imageSrc") + Properties.ImageQuality);
            }
        }

        if (mainPageModel.getTitleList() != null) {
            for (Map titleMap : mainPageModel.getTitleList()) {
                titleMap.replace("imageSrc", (String) titleMap.get("imageSrc") + Properties.ImageHighQuality);
            }
        }

        return mainPageModel.jsonSerialize();
    }

    /**
     * @Description: 获取除正文之外的其他信息
     */
    @Override
    public String getPageOtherInfo(int userId, int pageId) {
        Map<String, Object> pageOtherInfoMap = pageDao12.getPageOtherInfo(userId, pageId);
        List<Map<String, Object>> recomArtcList = (List<Map<String, Object>>) pageOtherInfoMap.get("recomArtc"); //推荐文章数组
        List<Map<String, Object>> comFirPageList = (List<Map<String, Object>>) pageOtherInfoMap.get("comFirPage"); //第一页评论列表

        Map<String, Object> getPageOtherInfoMap = new HashMap<>();

        /**
         * 推荐文章标题图片URL处理
         */
        for (Map tempMap : recomArtcList) {
            tempMap.replace("imageSrc", (String) tempMap.get("imageSrc") + Properties.ImageQuality);
            tempMap.replace("pageDate", TimeFormat.convertTimeToFormat((Date) tempMap.get("pageDate")));
        }

        /**
         * 评论列表用户头像URL处理
         */
        for (Map tempMap : comFirPageList) {
            String userPhoto = (String) tempMap.get("userPhoto");
            tempMap.replace("userPhoto", userPhoto + Properties.ImageLowQuality);
        }

        getPageOtherInfoMap.put("recomArtc", recomArtcList);
        getPageOtherInfoMap.put("comFirPage", comFirPageList);
        getPageOtherInfoMap.put("praNum", (int) pageOtherInfoMap.get("praNum"));
        getPageOtherInfoMap.put("criNum", (int) pageOtherInfoMap.get("criNum"));
        getPageOtherInfoMap.put("userChoice", (int) pageOtherInfoMap.get("userChoice"));
        getPageOtherInfoMap.put("typeBgImgSrc", (String) pageOtherInfoMap.get("typeBgImgSrc"));
        // getPageOtherInfoMap.put("adPicUrl", (String) pageOtherInfoMap.get("adPicUrl"));
        // getPageOtherInfoMap.put("adLink", (String) pageOtherInfoMap.get("adLink"));
        getPageOtherInfoMap.put("isSubscri", (boolean) pageOtherInfoMap.get("isSubscri"));
        getPageOtherInfoMap.put("comNum", (int) pageOtherInfoMap.get("comNum"));
        return JSON.toJSONString(getPageOtherInfoMap);
    }

    /**
     * @Description: 新增一条评论或回复
     */
    @Override
    public String setPageComment(JSONObject jsonObject) {
        int commentId = pageDao12.setPageComment(jsonObject);
        boolean result = (commentId == 0) ? false : true;
        Map<String, Object> setPageCommentMap = new HashMap<>();
        setPageCommentMap.put("commentOK", result);
        setPageCommentMap.put("commentId", commentId);

        return JSON.toJSONString(setPageCommentMap);
    }

    /**
     * @description: 新增一条评论或回复或改变一条评论的点赞数
     */
    @Override
    public String setPageComPraise(JSONObject jsonObject) {
        Map<String, Object> setPageComPraiseMap = new HashMap<>();
        setPageComPraiseMap.put("commentOK", pageDao12.setPageComPraise(jsonObject));

        return JSON.toJSONString(setPageComPraiseMap);
    }

    /**
     * @Description: 在文章中对三级分类信息进行评论和提供信息源
     */
    @Override
    public boolean postComInPage(JSONObject jsonObject) {
        int userId = jsonObject.getIntValue("userId"); // 用户ID
        String wantedInfo = jsonObject.getString("wantedInfo"); // 用户想要的信息
        String infoSource = jsonObject.getString("infoSource"); // 信息源

        // 如果想要的信息为null
        if (wantedInfo == null) {
            wantedInfo = "";
        }
        // 如果信息源为null
        if (infoSource == null) {
            infoSource = "";
        }

        return pageDao.postComInPage(userId, wantedInfo, infoSource);
    }

    /*--------------------------------------复用version1.1的Service层部分功能-------------------------------------------------*/

}
